package hu.myai.util;

import hu.myai.model.db.AxHistory;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;

public class DownloadUtil {

	private static final ILogger log = LoggerFactory.getLogger(DownloadUtil.class);

	private WebNoCookies webNoCookies = new WebNoCookies();

	public List<String> getASXCompanyList() {

		// symbol list
		List<String> symbolList = new ArrayList<String>();

		try {
			String myUrl = new String("http://www.asx.com.au/asx/downloadCsv/ASXListedCompanies.csv");

			// read date from web
			InputStream rawInStream = webNoCookies.getURLGetString(new URL(myUrl));

			/** Error handling: not data was read */
			if (rawInStream == null) {
				return null;
			}

			BufferedReader response = new BufferedReader(new InputStreamReader(rawInStream));

			String line = null;
			// remove the heather
			for (int i = 0; i < 4; i++)
				line = response.readLine();
			// Start EntityManagerFactory

			// store in db
			while (line != null && !line.equals("") && line.indexOf(",") != -1) {

				StringTokenizer tokens = new StringTokenizer(line, ",\n");
				if (tokens.countTokens() >= 2) {

					// companyName
					tokens.nextToken();
					// symbol
					symbolList.add(tokens.nextToken());
					// group
					tokens.nextToken();
				}
				line = response.readLine();
			}

			response.close();

		} catch (IOException ex) {
			// Use Log4j
			log.error("IOException thrown while initializing the ASX. Message is : " + ex.getMessage()); // LOG4J
			ex.printStackTrace();
			return null;
		}
		return symbolList;
	}

	public AxHistory getCandle(String symbol) {

		String line = "", myUrl = "";
		Double close = null;
		Double open = null;
		Double high = null;
		Double low = null;
		Integer volume = null;
		Double offer = null;
		Double bid = null;

		WebNoCookies webNoCookies = new WebNoCookies();

		AxHistory history = new AxHistory();

		try {
			myUrl = new String(
					"http://asx.com.au/asx/research/CompanyInfoSearchResults.jsp?searchBy=asxCode&allinfo=&asxCode="
							+ symbol + "#price");

			// read date from web
			InputStream rawInStream = webNoCookies.getURLGetString(new URL(myUrl));

			/** Error handling: not data was read */
			if (rawInStream == null) {
				return null;
			}

			BufferedReader response = new BufferedReader(new InputStreamReader(rawInStream));

			line = response.readLine();

			while (line != null) {
				line = response.readLine();

				if (line.contains(">" + symbol + "<")) {
					line = response.readLine();
					close = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));
					line = response.readLine();
					// change indicator

					line = response.readLine();
					bid = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));

					line = response.readLine();
					offer = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));

					line = response.readLine();
					open = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));

					line = response.readLine();
					high = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));

					line = response.readLine();
					low = new Double(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')));

					line = response.readLine();
					volume = new Integer(line.substring(line.indexOf('>') + 1, line.lastIndexOf('<')).replaceAll(",",
							""));

					break;
				}
			}

			response.close();

			// consolidate the result
			if (offer == 0.0)
				offer = null;
			if (bid == 0.0)
				bid = null;
			if (open == 0.0)
				open = close;
			if (high == 0.0)
				high = close;
			if (low == 0.0)
				low = close;

			history.setSymbol(symbol);

			Date date = new Date();
			history.setDate(date);

			history.setOpen(open);
			history.setHigh(high);
			history.setLow(low);
			history.setClose(close);
			history.setVolume(volume);
			history.setBookMaxBuy(bid);
			history.setBookMinSell(offer);

		} catch (IOException ex) {
			// Use Log4j
			log.error("IOException thrown while initializing the ASX. Message is : " + ex.getMessage());
			return null;
		}
		return history;
	}

	public boolean getPic(String prefix, String symbol, String posfix) {

		String myUrl = new String(
				"http://bigcharts.marketwatch.com/charts/big.chart?symb=AU:"
						+ symbol
						+ "&ma=4&maval=9&uf=0&lf=256&lf2=128&lf3=268435456&type=4&size=2&style=320&time=5&freq=1&nosettings=1&mocktick=1");

		log.debug(myUrl);
		try {

			BufferedInputStream gifPic = new BufferedInputStream(webNoCookies.getURLGetString(new URL(myUrl)));

			// File gifFile = new
			// File("chart"+File.pathSeparator+symbol+".gif");

			FileOutputStream fos;
			DataOutputStream ds;

			File picFolder = new File(prefix);
			picFolder.mkdir();

			File picFile = new File(picFolder, symbol + "_" + posfix + ".gif");

			fos = new FileOutputStream(picFile);

			// Wrap the FileOutputStream with a
			// DataOutputStream to obtain its writeInt()
			// method.
			ds = new DataOutputStream(fos);

			byte buffer[] = new byte[4096];

			int bytesRead;

			while ((bytesRead = gifPic.read(buffer)) > 0) {
				ds.write(buffer, 0, bytesRead);
				ds.flush();
			}

			ds.close();

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}
}
